package com.yehebl.orm;

import com.yehebl.orm.config.IConfig;
import com.yehebl.orm.data.common.xml.manager.XmlSqlManager;
import com.yehebl.orm.data.mysql.MySqlSqlManager;
import com.yehebl.orm.dto.ClassInfo;
import com.yehebl.orm.enums.DataType;
import com.yehebl.orm.enums.RunMode;
import com.yehebl.orm.manager.ReadClassManager;
import com.yehebl.orm.manager.ScanManager;
import com.yehebl.orm.util.LogUtil;

import java.io.File;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;

/**
 * 框架运行入口
 */
public class DsMain {
	private static final Set<IConfig> loadConfigSet = new HashSet<>();

	public static void loadConfig(IConfig config) {
		if (loadConfigSet.contains(config)) {
			return;
		}
		loadConfigSet.add(config);
		LogUtil.printInfo("开始启动...");
		LogUtil.printInfo("当前启动模式为" + config.getRunMode() + "模式");
		// 扫描类
		String scanStr = config.getScanPackage();
		String[] scanPackages = scanStr.split(",");
		Set<Class<?>> classes = new LinkedHashSet<>();
		for (String scanPackage : scanPackages) {
			LogUtil.printInfo("扫描数据库实体类[" + scanPackage + "]下class");
			classes.addAll(ScanManager.getClasses(scanPackage));
		}

		for (Class<?> clazz : classes) {
			ReadClassManager.readEntityClass(clazz, config);
		}
		for (ClassInfo ci : ReadClassManager.map.values()) {
			LogUtil.printInfo("初始化实体[" + ci.getClazz().getName() + "]的基础SQL语句");
			if (DataType.MYSQL.equals(config.getDataType())) {
				MySqlSqlManager.initSql(ci);
			}
		}
		// 扫描xml文件
		if (config.getScanXml() != null) {
			Set<String> resultList = new HashSet<>();
			LogUtil.printInfo("扫描xml文件");
			String[] scanXmls = config.getScanXml().split(",");
			String path;
			Set<String> xmlSet= new HashSet<>();
			for(String scanXml :scanXmls) {
				if(scanXml.startsWith("classpath:")) {
					scanXml=scanXml.substring(10);
					ScanManager.getXml(scanXml, xmlSet);
				}else {
					path = System.getProperty("user.dir");
					XmlSqlManager.scanQueryXmlFile(path+File.separator+scanXml, resultList);
				}
			}
			for (String string : xmlSet) {
				String path1 = Objects.requireNonNull(DsMain.class.getResource("/" + string)).getPath();
				if(path1.contains("jar!")) {
					XmlSqlManager.readXml(path1,DsMain.class.getResourceAsStream("/"+string));
				}else {
					resultList.add(path1);
				}
			}
			for (String fileUrl : resultList) {
				XmlSqlManager.readXml(fileUrl);
			}
			if (RunMode.DEBUG.equals(config.getRunMode())) {
				LogUtil.printInfo("DEBUG模式默认开启XML热更新");
				XmlSqlManager.HotXml(resultList);
			}
		}
		LogUtil.printInfo("启动完成...");
	}
}
